import config from '@/config';
import { getToken } from '@/utils/auth';

const { API_BASE_URL, API_TIMEOUT } = config;

const request = (options = {}) => {
	return new Promise((resolve, reject) => {
		const {
			url,
			method = 'GET',
			data = {},
			header = {},
			showLoading = true,
			hideErrorToast = false
		} = options;

		if (!url) {
			reject(new Error('请求地址不能为空'));
			return;
		}

		if (showLoading) {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
		}

		const token = getToken();

		uni.request({
			url: `${API_BASE_URL}${url}`,
			method,
			data,
			timeout: API_TIMEOUT,
			header: {
				'Content-Type': 'application/json',
				...(token ? { Authorization: token } : {}),
				...header
			},
			success: (res) => {
				const responseData = res.data || {};
				if (res.statusCode === 200 && responseData.success) {
					resolve(responseData.data);
				} else {
					const message =
						responseData.errorMsg || `请求失败（${res.statusCode}）`;
					if (!hideErrorToast) {
						uni.showToast({
							title: message,
							icon: 'none'
						});
					}
					reject(new Error(message));
				}
			},
			fail: (err) => {
				const message = err.errMsg || '网络异常，请稍后重试';
				if (!hideErrorToast) {
					uni.showToast({
						title: message,
						icon: 'none'
					});
				}
				reject(new Error(message));
			},
			complete: () => {
				if (showLoading) {
					uni.hideLoading();
				}
			}
		});
	});
};

export default request;

